package com.gui.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.gui.hosp.repository.DepartmentRepository;
import com.gui.hosp.service.DepartmentService;
import com.gui.model.hosp.Department;
import com.gui.vo.hosp.DepartmentQueryVo;
import com.gui.vo.hosp.DepartmentVo;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author GodLamp
 * @date 2022/10/21 18:24
 */
@Service
public class DepartmentServiceImpl implements DepartmentService {
    @Resource
    private DepartmentRepository departmentRepository;

    /**
     * 上传科室
     * @param params
     */
    @Override
    public void save(Map<String, Object> params) {
        //转换成对象（先转换成JSON对象，再转为Department对象）
        Department department = JSONObject.parseObject(JSONObject.toJSONString(params), Department.class);

        //从数据库中查询是否存在
        Department depart = departmentRepository.getDepartmentByHoscodeAndDepcode(
                department.getHoscode(),
                department.getDepcode()
        );

        //判断
        if (depart != null) {
            depart.setUpdateTime(new Date());
            depart.setIsDeleted(0);

            departmentRepository.save(depart);
        } else {
            department.setCreateTime(new Date());
            department.setUpdateTime(new Date());
            department.setIsDeleted(0);

            departmentRepository.save(department);
        }

    }

    @Override
    public Page<Department> findPageDepart(int page, int limit, DepartmentQueryVo vo) {
        //转换对象
        Department department = new Department();
        BeanUtils.copyProperties(vo, department);
        department.setIsDeleted(0);

        //创建Pageable对象，设置当前页以及分页数
        //0是第一页
        Pageable pageable = PageRequest.of(page - 1, limit);

        //创建Example对象,设置查询条件
        ExampleMatcher exampleMatcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true);

        Example<Department> departmentExample = Example.of(department, exampleMatcher);

        return departmentRepository.findAll(departmentExample, pageable);
    }

    @Override
    public void remove(String hoscode, String depcode) {
        Department department = departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
        if (department != null) {
            departmentRepository.deleteById(department.getId());
        }

    }

    /**
     * 根据医院编号，查询该医院的所有科室
     * @param hoscode
     * @return
     */
    @Override
    public List<DepartmentVo> findDeptTree(String hoscode) {
        //封装最后返回结果
        List<DepartmentVo> list = new ArrayList<>();

        //查询所有科室
        Example<Department> example = Example.of(new Department().setHoscode(hoscode));
        List<Department> departments = departmentRepository.findAll(example);

        //根据大科室编号，对所有科室进行分组
        Map<String, List<Department>> collect = departments.stream().collect(Collectors.groupingBy(Department::getBigcode));

        //遍历所有科室分组，进行非封装
        for (Map.Entry<String, List<Department>> entry : collect.entrySet()) {
            DepartmentVo vo = new DepartmentVo();
            //封装大科室信息
            vo.setDepcode(entry.getKey());
            vo.setDepname(entry.getValue().get(0).getBigname());
            //封装小科室信息
            List<DepartmentVo> voList = new ArrayList<>();
            for (Department department : entry.getValue()) {
                DepartmentVo departmentVo = new DepartmentVo();

                departmentVo.setDepcode(department.getDepcode());
                departmentVo.setDepname(department.getDepname());
                voList.add(departmentVo);
            }
            vo.setChildren(voList);
            //添加到最终结果集中
            list.add(vo);
        }
        return list;
    }

    @Override
    public String getDepName(String hoscode, String depcode) {
        Department department = departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
        if (department == null) {
            return null;
        }

        return department.getDepname();
    }
}
